<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use OSS\OssClient;
use think\Controller;
use think\Image;

/**
 * 阿里云上传
 */
class Aliuploadimage extends Controller
{
    /**
     * 上传图片
     * User:@hang
     */
    public function setImages($file){
        if(empty($file)){
            return ['code'=>'500','msg'=>'请上传图片文件','data'=>[]];
        }
        $IndexTableModel = New IndexTableModel();
        $configValue = $IndexTableModel->getList('fa_config_tripartite',"`config_key` in('alaccesskeyoss','alaccesskeysecretoss','alossendpointoss','alossbucketoss')",'config_key,config_value','id asc');
        $arr = array();
        if(!empty($configValue)){
            foreach ($configValue as $k=>$v){
                $arr[$v['config_key']] = $v['config_value'];
            }
        }
        $resResult = Image::open($file);
        // 尝试执行
        try {
            $config['KeyId'] = $arr['alaccesskeyoss'];
            $config['KeySecret'] = $arr['alaccesskeysecretoss'];
            $config['Bucket'] = $arr['alossbucketoss'];
            $config['Endpoint'] = $arr['alossendpointoss'];
            //实例化对象 将配置传入
            $ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
            //这里是有sha1加密 生成文件名 之后连接上后缀
            $fileName = 'rearend/'.sha1(date('YmdHis', time()) . uniqid()) . '.' . $resResult->type();
            //执行阿里云上传
            $result = $ossClient->uploadFile($config['Bucket'], $fileName, $file->getInfo()['tmp_name']);
            if(isset($result['info']['url'])){
                if(!empty($result['info']['url'])){
                    return ['code'=>'200','msg'=>'阿里云OSS上传图片成功','data'=>['url'=>$result['info']['url']]];
                }else{
                    return ['code'=>'500','msg'=>'阿里云OSS上传图片数据为空','data'=>[]];
                }
            }else{
                return ['code'=>'500','msg'=>'阿里云OSS上传图片失败','data'=>[]];
            }
        } catch (OssException $e) {
            return $e->getMessage();
        }
    }






}